package org.springboot.rocketmq.config;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class RocketMqOriginalConfig {

	private static final Logger logger = LoggerFactory.getLogger(RocketMqOriginalConfig.class);

	@Value("${rocketmq.two.name-server}")
    private String twoServer;
    @Value("${rocketmq.two.producer.group}")
    private String twoProducerGroup;

    public DefaultMQProducer producer;

	public void send(String topic, String tag, String value) {
		try {
			if (producer == null) {
				producer = initProducer();
			}
			// 创建Message实例
		    Message msg = new Message(topic , tag, (value).getBytes(RemotingHelper.DEFAULT_CHARSET));
			producer.send(msg);
		} catch (Exception e) {
			logger.error("rocket消息 {} 发送异常！ topic: {} tag {}", value, topic, tag, e);
			if (producer != null) {
				producer.shutdown();
			}
			// 不知道这个错误怎么处理，先抛出去吧
			throw new RuntimeException(e);
		}
	}

	private DefaultMQProducer initProducer() throws MQClientException {
	    DefaultMQProducer producer = new DefaultMQProducer(twoProducerGroup);
	    producer.setUnitName("two");
	    producer.setNamesrvAddr(twoServer);
	    producer.start();
		return producer;
	}

}
